<?php

namespace Api\Controller;
use Api\Event\TypeEvent;
use Common\Controller\PcHomeBaseController;

class OauthController extends PcHomeBaseController
{
    protected $user_model;
    protected $oauthUser_model;

    public function _initialize() {
        //parent::_initialize();  //无界面显示
        $this->user_model = D("Common/User");
        $this->oauthUser_model = D("Common/OauthUser");
    }

    // 第三方平台登陆
    public function login() {
        $type = I('get.type');
        empty($type) && $this->error('参数错误');
        $_SESSION['login_http_referer']=$_SERVER["HTTP_REFERER"];
        $sns = \ThinkOauth::getInstance($type);
        redirect($sns->getRequestCodeURL());
    }

    //授权回调地址
    public function callback() {

        $type = I('get.type');
        $code = I('get.code');

        empty($type) && $this->error('参数错误');
        if(empty($code)){
            redirect(__ROOT__ . "/");
        }
        //加载ThinkOauth类并实例化一个对象
        $sns  = \ThinkOauth::getInstance($type);
        //腾讯微博需传递的额外参数
        $extend = null;
        if ($type == 'tencent') {
            $extend = array('openid' => $this->I('get.openid'), 'openkey' => $this->I('get.openkey'));
        }

        //请妥善保管这里获取到的Token信息，方便以后API调用
        //调用方法，实例化SDK对象的时候直接作为构造函数的第二个参数传入
        //如： $qq = ThinkOauth::getInstance('qq', $token);
        $token = $sns->getAccessToken($code , $extend);

        //获取当前登录用户信息
        if (is_array($token)) {
            $user_info = A('Type', 'Event')->$type($token);
            $oauth_bang = session('oauth_bang');
            if (!empty($oauth_bang)) {
                $this->_bang_handle($user_info, $type, $token);
            } else {
                $this->_login_handle($user_info, $type, $token);
            }
        } else {
            $this->success('登录失败',$this->_get_login_redirect());
        }
    }

    function bang() {
        $type = I('get.type');

        if (x_is_user_login()) {
            empty($type) && $this->error('参数错误');
            $sns = \ThinkOauth::getInstance($type);
            session('oauth_bang', 1);
            redirect($sns->getRequestCodeURL());
        } else {
            $this->error('您还没有登录');
        }
    }

    //绑定第三方账号
    private function _bang_handle($user_info, $type, $token) {
        $current_uid = x_get_user_id();
        $type=strtolower($type);
        $find_oauth_user = $this->oauthUser_model->where(array('type'=>$type,'openid'=>$token['openid']))->find();
        if ($find_oauth_user) {
            if($find_oauth_user['user_id'] == $current_uid) {
                $this->error('您之前已经绑定过此账号', U('User/Center/bang'),0);exit;
            }else{
                $this->error('该帐号已被本站其他账号绑定', U('User/Center/bang'),0);exit;
            }
        }

        if ($current_uid) {
            //第三方用户表中创建数据
            $new_oauth_user_data = array(
                'type'        => $type,
                'name'        => $user_info['name'],
                'head_img'    => $user_info['head'],
                'user_id'     => $current_uid,
                'login_times' => 1,
                'status'      => 1,
                'openid'      => $token['openid'],
                'create_time' => time(),
                'access_token'    => $token['access_token'],
                'last_login_time' => time(),
                'last_login_ip'   => get_client_ip(0, true),
            );
            $new_oauth_user_id = $this->oauthUser_model->add($new_oauth_user_data);
            if ($new_oauth_user_id) {
                $this->success('绑定成功', U('User/Center/bang'));
            }else{
                $this->error('绑定失败', U('User/Center/bang'));
            }
        }else{
            $this->error('绑定失败', U('User/Center/bang'));
        }
    }

    //登陆
    private function _login_handle($user_info, $type, $token) {
        $type=strtolower($type);
        $find_oauth_user = $this->oauthUser_model->where(array('type'=>$type,'openid'=>$token['openid']))->find();
        $need_register = true;
        if($find_oauth_user){
            $find_user = $this->user_model->where(array("user_id"=>$find_oauth_user['user_id']))->find();
            if ($find_user) {
                $need_register = false;
                if ($find_user['status'] == 0) {
                    $this->error('您可能已经被列入黑名单，请联系网站管理员解决', $this->_get_login_redirect());
                } else {
                    //更新字段
                    $data = array(
                        'last_login_time' => time(),
                        'last_login_ip' => get_client_ip(0, true),
                    );
                    $this->user_model->where(array('user_id'=>$find_user["user_id"]))->save($data);
                    session('user', $find_user);
                    redirect($this->_get_login_redirect());
                }
            }else{
                $need_register = true;
            }
        }

        if ($need_register) {
            //本地用户中创建对应一条数据
            $new_user_data = array(
                'nickname'    => $user_info['name'],
                'head_img'    => $user_info['head'],
                'create_time' => time(),
                'status'      => 1,
                'last_login_time' => time(),
                'last_login_ip'   => get_client_ip(0, true),
            );
            $new_user_id = $this->user_model->add($new_user_data);
            if($new_user_id){
                //第三方用户表中创建数据
                $new_oauth_user_data = array(
                    'ype'        => $type,
                    'name'        => $user_info['name'],
                    'head_img'    => $user_info['head'],
                    'user_id'     => $new_user_id,
                    'login_times' => 1,
                    'status'      => 1,
                    'openid'      => $token['openid'],
                    'create_time' => time(),
                    'access_token'    => $token['access_token'],
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                );
                $new_oauth_user_id = $this->oauthUser_model->add($new_oauth_user_data);
                if($new_oauth_user_id){
                    $new_user_data['user_id'] = $new_user_id;
                    session('user', $new_user_data);
                    redirect($this->_get_login_redirect());
                }else{
                    $this->user_model->where(array('user_id'=>$new_user_id))->delete();
                    $this->error('登陆失败', $this->_get_login_redirect());
                }
            }else{
                $this->error('登陆失败', $this->_get_login_redirect());
            }

        }
    }

    private function _get_login_redirect() {
        $login_http_referer = session('login_http_referer');
        return empty($login_http_referer) ? __ROOT__ . '/' : $login_http_referer;
    }

}